package cn.edu.jxau.test;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 稀疏向量
 * 
 * @author 付大石
 */
public class SparseVector {

    public static void main(String[] args) {

        SparseVector[] matrix = new SparseVector[5];
        for (int i = 0; i < matrix.length; i++) {
            matrix[i] = new SparseVector();
        }

        // 初始化矩阵 //
        matrix[0].put(1, 0.9);
        matrix[1].put(2, 0.36);
        matrix[1].put(3, 0.36);
        matrix[1].put(4, 0.18);
        matrix[2].put(3, 0.9);
        matrix[3].put(0, 0.9);
        matrix[4].put(0, 0.47);
        matrix[4].put(2, 0.47);

        double[] x = new double[] { 0.05, 0.04, 0.36, 0.37, 0.19 };
        double[] result = new double[x.length];

        for (int i = 0; i < matrix.length; i++) {
            result[i] = matrix[i].dot(x);
        }
        System.out.println(Arrays.toString(result));
    }

    private HashMap<Integer, Double> st;

    public SparseVector() {
        st = new HashMap<>();
    }

    public int size() {
        return st.size();
    }

    public double get(int i) {

        Double d = st.get(i);
        return d == null ? 0.0 : d;
    }

    public void put(int i, double d) {
        st.put(i, d);
    }

    public double dot(double[] vector) {

        double sum = 0.0;
        for (int i : st.keySet()) {
            sum += vector[i] * st.get(i);
        }
        return sum;
    }
}
